package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.TestRankBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.RankAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.GlideCircle;
import de.greenrobot.event.EventBus;

public class RankActivity extends BaseActivity implements View.OnClickListener {

    int page = 1;
    boolean isLastPage = false, isSlidingToLast, isMore = false;
    boolean isFirst;
    boolean isSecond;
    RankAdapter adapter;
    UserPresenter presenter;
    String userid, libid, interval = "1";
    List<TestRankBean.DataEntity> list;
    UserBean.DataEntity dataEntity;
    int maxPage = 10;
    boolean isActivity;
    boolean isLimit;
    String libName;

    @Bind(R.id.btn_country)
    TextView btnCountry;
    @Bind(R.id.btn_area)
    TextView btnArea;
    @Bind(R.id.btn_exit)
    ImageView btnExit;
    @Bind(R.id.line_today)
    View lineToday;
    @Bind(R.id.btn_today)
    LinearLayout btnToday;
    @Bind(R.id.line_week)
    View lineWeek;
    @Bind(R.id.btn_week)
    LinearLayout btnWeek;
    @Bind(R.id.line_month)
    View lineMonth;
    @Bind(R.id.btn_month)
    LinearLayout btnMonth;
    @Bind(R.id.line_all)
    View lineAll;
    @Bind(R.id.btn_all)
    LinearLayout btnAll;
    @Bind(R.id.rank_list)
    RecyclerView rankList;
    @Bind(R.id.rank_second_icon)
    ImageView rankSecondIcon;
    @Bind(R.id.rank_second_name)
    TextView rankSecondName;
    @Bind(R.id.rank_secon_spend_time)
    TextView rankSeconSpendTime;
    @Bind(R.id.rank_second_percent)
    TextView rankSecondPercent;
    @Bind(R.id.rank_first_icon)
    ImageView rankFirstIcon;
    @Bind(R.id.rank_first_name)
    TextView rankFirstName;
    @Bind(R.id.rank_first_spend_time)
    TextView rankFirstSpendTime;
    @Bind(R.id.rank_first_percent)
    TextView rankFirstPercent;
    @Bind(R.id.rank_third_icon)
    ImageView rankThirdIcon;
    @Bind(R.id.rank_third_name)
    TextView rankThirdName;
    @Bind(R.id.rank_third_spend_time)
    TextView rankThirdSpendTime;
    @Bind(R.id.rank_third_percent)
    TextView rankThirdPercent;
    @Bind(R.id.rank_first_score)
    TextView rankFirstScore;
    @Bind(R.id.rank_second_score)
    TextView rankSecondScore;
    @Bind(R.id.rank_third_score)
    TextView rankThirdScore;
    @Bind(R.id.rank_mine_rank)
    TextView rankMineRank;
    @Bind(R.id.rank_mine_icon)
    ImageView rankMineIcon;
    @Bind(R.id.rank_mine_name)
    TextView rankMineName;
    @Bind(R.id.rank_mine_score)
    TextView rankMineScore;
    @Bind(R.id.rank_mine_time)
    TextView rankMineTime;
    @Bind(R.id.rank_mine_gender)
    ImageView rankMineGender;
    @Bind(R.id.rank_mine_beat)
    TextView rankMineBeat;
    @Bind(R.id.rank_refresh)
    SwipeRefreshLayout rankRefresh;
    @Bind(R.id.rank_second)
    LinearLayout rankSecond;
    @Bind(R.id.rank_first)
    LinearLayout rankFirst;
    @Bind(R.id.rank_third)
    LinearLayout rankThird;
    @Bind(R.id.rank_second_text)
    TextView rankSecondText;
    @Bind(R.id.rank_first_text)
    TextView rankFirstText;
    @Bind(R.id.rank_third_text)
    TextView rankThirdText;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.relativeLayout_my_rank)
    RelativeLayout relativeLayoutMyRank;
    @Bind(R.id.textview_all)
    TextView textviewAll;
    @BindColor(R.color.white)
    int white;
    @Bind(R.id.linearlayout_my_rank)
    LinearLayout linearlayoutMyRank;
    @Bind(R.id.linearlayout_my_rank_time)
    LinearLayout linearlayoutMyRankTime;
    @Bind(R.id.textview_my_rank_empty)
    TextView textviewMyRankEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        dataEntity = new UserBean.DataEntity();

        initClickBtn();

        initList();
        initIntent();
        initButton();
        btnCountry.setTextColor(getResources().getColor(R.color.colorPrimary));
        btnCountry.setBackgroundResource(R.drawable.bg_rank_left_press);
    }


    @Override
    protected void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        libid = intent.getStringExtra(Constant.TO_RANK_LIBID);
        libName = intent.getStringExtra(Constant.TO_RANK_TITLE);
        isActivity = intent.getBooleanExtra(Constant.TO_RANK_IS_ACTIVITY, false);
        isFirst = intent.getBooleanExtra(Constant.TO_TEST_RANK_IF_FIRST, false);
        isSecond = intent.getBooleanExtra(Constant.TO_TEST_RANK_IF_SECOND, false);
        initModel();
    }

    private void initList() {
        list = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        adapter = new RankAdapter(list);
        rankList.setHasFixedSize(true);
        rankList.setAdapter(adapter);
        rankList.setLayoutManager(manager);

        rankRefresh.setColorSchemeResources(R.color.colorPrimary);
        rankRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                list.clear();
                adapter.notifyDataSetChanged();
                presenter.testRank(libid, userid, interval, "10", String.valueOf(page));
                isLastPage = false;
                isLimit = false;
                rankRefresh.setRefreshing(false);
            }
        });

        rankList.addOnScrollListener(new RecyclerView.OnScrollListener() {
                                         //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
                                         @Override
                                         public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                             LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                                             // 当不滚动时
                                             if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                                                 //获取最后一个完全显示的ItemPosition
                                                 int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                                                 int totalItemCount = manager.getItemCount();
                                                 // 判断是否滚动到底部，并且是向右滚动
                                                 if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                                                     //加载更多功能的代码
                                                     isMore = true;
                                                     if (isFirst) {
                                                             page++;
                                                         if (page <= 20) {
                                                             presenter.testRank(libid, userid, interval, "10", String.valueOf(page));
                                                         }
                                                         if (!isLastPage && !isLimit && page == 22) {
                                                             DeviceUtil.MyToast(RankActivity.this, "排名只显示前200名");
                                                             isLimit = true;
                                                             isLastPage = true;
                                                         }
                                                     } else if (isSecond) {
                                                             page++;
                                                         if (page <= 5) {
                                                             presenter.testRank(libid, userid, interval, "10", String.valueOf(page));
                                                         }
                                                         if (!isLastPage && !isLimit && page == 7) {
                                                             DeviceUtil.MyToast(RankActivity.this, "排名只显示前50名");
                                                             isLimit = true;
                                                             isLastPage = true;
                                                         }
                                                     } else {
                                                         if (!isLastPage) {
                                                             page++;
                                                             presenter.testRank(libid, userid, interval, "10", String.valueOf(page));
                                                         }
                                                     }
                                                 }
                                             }
                                         }

                                         @Override
                                         public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                             super.onScrolled(recyclerView, dx, dy);
                                             //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                                             if (dy > 0) {
                                                 //大于0表示，正在向右滚动
                                                 isSlidingToLast = true;
                                             } else {
                                                 //小于等于0 表示停止或向左滚动
                                                 isSlidingToLast = false;
                                             }

                                         }
                                     }

        );
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取排行榜数据
     *
     * @param bean
     */
    public void onEventMainThread(TestRankBean bean) {
        hideLoading();
        linearlayoutMyRank.setVisibility(View.GONE);
        linearlayoutMyRankTime.setVisibility(View.GONE);
        textviewMyRankEmpty.setVisibility(View.GONE);
        if (bean.getMyrank() == null) {
            textviewMyRankEmpty.setVisibility(View.VISIBLE);
        } else {
            linearlayoutMyRankTime.setVisibility(View.VISIBLE);
            linearlayoutMyRank.setVisibility(View.VISIBLE);
        }
        if (bean.getReturn_code() == 0) {

            list.addAll(bean.getData());
            adapter.notifyDataSetChanged();
            if (!isMore) {
                rankFirst.setVisibility(View.VISIBLE);
                rankSecond.setVisibility(View.VISIBLE);
                rankThird.setVisibility(View.VISIBLE);
                switch (bean.getData().size()) {
                    case 0: {
                        rankFirst.setVisibility(View.INVISIBLE);
                        rankSecond.setVisibility(View.INVISIBLE);
                        rankThird.setVisibility(View.INVISIBLE);
                        break;
                    }
                    case 1: {
                        initFirst(bean.getData().get(0));
                        rankSecond.setVisibility(View.INVISIBLE);
                        rankThird.setVisibility(View.INVISIBLE);
                        break;
                    }
                    case 2: {
                        initFirst(bean.getData().get(0));
                        initSecond(bean.getData().get(1));
                        rankThird.setVisibility(View.INVISIBLE);
                        break;
                    }
                    default: {
                        initFirst(bean.getData().get(0));
                        initSecond(bean.getData().get(1));
                        initThird(bean.getData().get(2));
                        break;
                    }
                }
            }

            if (bean.getMyrank() != null) {
                rankMineRank.setText(String.valueOf(bean.getMyrank().getRank()));
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                String icon = dataEntity.getUthumb();
                Glide
                        .with(this)
                        .load(icon)
                        .placeholder(R.mipmap.drawer_icon_unlogin)
                        .transform(new GlideCircle(this))
                        .into(rankMineIcon);

                rankMineName.setText(dataEntity.getNickname());
                if (dataEntity.getGender().equals("1")) {
                    rankMineGender.setImageResource(R.mipmap.rank_male);
                } else {
                    rankMineGender.setImageResource(R.mipmap.rank_female);
                }

                int time = Integer.parseInt(bean.getMyrank().getSpend_time());
                String timeStr = time / 60 + "分" + time % 60 + "秒";
                rankMineTime.setText(timeStr);
                rankMineScore.setText(bean.getMyrank().getScore() + "分");

                double rank = bean.getMyrank().getRank();
                double total = Double.parseDouble(bean.getMyrank().getTotal());
                double percent;
                if (Double.compare(rank, total) == 0 && total == 1) {
                    percent = 100;
                } else {
                    percent = (total - rank) * 100 / (total - 1);
                }
                DecimalFormat df = new DecimalFormat("######0");
                rankMineBeat.setText(df.format(percent) + "%");
            }

        } else if (bean.getReturn_code() == -203) {
            DeviceUtil.MyToast(this, "已经是最后一页");
            isLastPage = true;
        } else if (bean.getReturn_code() == -204) {
            initFirstNull();
            initSecondNull();
            initThirdNull();
            initMineNull();
        }

    }

    private void initMineNull() {
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        rankMineName.setText(user.getNickname());
        DeviceUtil.Log(user.getGender());
        if (user.getGender().equals("1")) {
            rankMineGender.setImageResource(R.mipmap.rank_male);
        } else if (user.getGender().equals("2")) {
            rankMineGender.setImageResource(R.mipmap.rank_female);
        } else {
            rankMineGender.setVisibility(View.GONE);
        }
        rankMineScore.setText("0分");
        rankMineBeat.setText("0%");
        rankMineTime.setText("0分0秒");
    }

    private void initFirstNull() {
        rankFirstText.setVisibility(View.GONE);
        rankFirstIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
        rankFirstName.setText("暂无数据");
        rankFirstSpendTime.setText("0分0秒");
        rankFirstPercent.setText("0%");
        rankFirstScore.setText("0分");
    }

    private void initSecondNull() {
        rankSecondText.setVisibility(View.GONE);
        rankSecondIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
        rankSecondName.setText("暂无数据");
        rankSecondScore.setText("0分");
        rankSecondPercent.setText("0%");
        rankSeconSpendTime.setText("0分0秒");
    }

    private void initThirdNull() {
        rankThirdText.setVisibility(View.GONE);
        rankThirdIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
        rankThirdSpendTime.setText("0分0秒");
        rankThirdName.setText("暂无数据");
        rankThirdPercent.setText("0%");
        rankThirdScore.setText("0分");
    }

    private void initThird(TestRankBean.DataEntity bean) {
        Glide
                .with(this)
                .load(bean.getUthumb())
                .placeholder(R.mipmap.drawer_icon_unlogin)
                .transform(new GlideCircle(this))
                .into(rankThirdIcon);

        rankThirdName.setText(bean.getNickname() + "(探花)");
        String time = Integer.parseInt(bean.getSpend_time()) / 60 + "分" + Integer.parseInt(bean.getSpend_time()) % 60 + "秒";
        rankThirdSpendTime.setText(time);
        rankThirdScore.setText(bean.getScore() + "分");
        double rank = bean.getRank();
        double total = Double.parseDouble(bean.getTotal());
        double percent;
        if (Double.compare(rank, total) == 0 && total == 1) {
            percent = 100;
        } else {
            percent = (total - rank) * 100 / (total - 1);
        }

        DecimalFormat df = new DecimalFormat("######0");
        rankThirdPercent.setText(String.valueOf(df.format(percent)) + "%");
    }

    private void initFirst(TestRankBean.DataEntity bean) {

        Glide
                .with(this)
                .load(bean.getUthumb())
                .placeholder(R.mipmap.drawer_icon_unlogin)
                .transform(new GlideCircle(this))
                .into(rankFirstIcon);

        rankFirstScore.setText(bean.getScore() + "分");
        rankFirstName.setText(bean.getNickname() + "(状元)");
        String time = Integer.parseInt(bean.getSpend_time()) / 60 + "分" + Integer.parseInt(bean.getSpend_time()) % 60 + "秒";
        rankFirstSpendTime.setText(time);
        double rank = bean.getRank();
        double total = Double.parseDouble(bean.getTotal());
        double percent;
        if (Double.compare(rank, total) == 0 && total == 1) {
            percent = 100;
        } else {
            percent = (total - rank) * 100 / (total - 1);
        }

        DecimalFormat df = new DecimalFormat("######0");
        rankFirstPercent.setText(String.valueOf(df.format(percent)) + "%");
    }

    private void initSecond(TestRankBean.DataEntity bean) {

        Glide
                .with(this)
                .load(bean.getUthumb())
                .placeholder(R.mipmap.drawer_icon_unlogin)
                .transform(new GlideCircle(this))
                .into(rankSecondIcon);

        rankSecondScore.setText(bean.getScore() + "分");
        rankSecondName.setText(bean.getNickname() + "(榜眼)");
        String time = Integer.parseInt(bean.getSpend_time()) / 60 + "分" + Integer.parseInt(bean.getSpend_time()) % 60 + "秒";
        rankSeconSpendTime.setText(time);
        double rank = bean.getRank();
        double total = Double.parseDouble(bean.getTotal());
        double percent;
        if (Double.compare(rank, total) == 0 && total == 1) {
            percent = 100;
        } else {
            percent = (total - rank) * 100 / (total - 1);
        }

        DecimalFormat df = new DecimalFormat("######0");
        rankSecondPercent.setText(String.valueOf(df.format(percent)) + "%");
    }

    private void initModel() {
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();

        presenter = new UserPresenterImp();

        if (!isFirst && !isSecond) {
            LibListBean.DataEntity lib = new LibListBean.DataEntity();
            lib.readLibListIntoLocal(this);
            if (TextUtils.isEmpty(libid)) {
                libid = lib.getId();
            }
            if (TextUtils.isEmpty(libName)) {
                LibListBean.DataEntity dataEntity = new LibListBean.DataEntity();
                dataEntity.readLibListIntoLocal(this);
                mToolbar.setTitle("英雄榜-" + dataEntity.getTitle());
                mToolbar.setTitleTextColor(white);
                initLine(lineToday, 1);
            } else {
                if (isActivity) {
                    textviewAll.setText(libName);
                    btnToday.setVisibility(View.GONE);
                    btnWeek.setVisibility(View.GONE);
                    btnMonth.setVisibility(View.GONE);
                    initLine(lineAll, 4);
                    btnAll.setClickable(false);
                    interval = "4";
                } else {
                    mToolbar.setTitle("英雄榜-" + libName);
                    mToolbar.setTitleTextColor(white);
                }
            }


        } else {
            if (isFirst) {
                textviewAll.setText("“金轮-蓝钻杯”梳理知识大奖赛初赛排行榜");
            } else {
//                textviewAll.setText("“金轮-蓝钻杯”梳理知识大奖赛复赛排行榜");
                textviewAll.setText("“金轮-蓝钻杯”梳理知识大奖赛决赛排行榜");
            }
            btnToday.setVisibility(View.GONE);
            btnWeek.setVisibility(View.GONE);
            btnMonth.setVisibility(View.GONE);
            initLine(lineAll, 4);
            btnAll.setClickable(false);
            interval = "4";
        }
    }

    private void initClickBtn() {
        btnCountry.setOnClickListener(this);
        btnArea.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        btnToday.setOnClickListener(this);
        btnWeek.setOnClickListener(this);
        btnMonth.setOnClickListener(this);
        btnAll.setOnClickListener(this);
    }

    private void initButton() {
        btnCountry.setTextColor(getResources().getColor(R.color.white));
        btnCountry.setBackgroundResource(R.drawable.bg_rank_left);
        btnArea.setTextColor(getResources().getColor(R.color.white));
        btnArea.setBackgroundResource(R.drawable.bg_rank_right);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_area: {
                initButton();
                btnArea.setTextColor(getResources().getColor(R.color.colorPrimary));
                btnArea.setBackgroundResource(R.drawable.bg_rank_right_press);
                break;
            }
            case R.id.btn_country: {
                initButton();
                btnCountry.setTextColor(getResources().getColor(R.color.colorPrimary));
                btnCountry.setBackgroundResource(R.drawable.bg_rank_left_press);
                break;
            }
            case R.id.btn_exit: {
                finish();
                break;
            }
            case R.id.btn_today: {
                initLine(lineToday, 1);
                interval = "1";
                isMore = false;
                isSlidingToLast = false;
                break;
            }
            case R.id.btn_week: {
                initLine(lineWeek, 2);
                interval = "2";
                isMore = false;
                isSlidingToLast = false;
                break;
            }
            case R.id.btn_month: {
                initLine(lineMonth, 3);
                interval = "3";
                isMore = false;
                isSlidingToLast = false;
                break;
            }
            case R.id.btn_all: {
                initLine(lineAll, 4);
                interval = "4";
                isMore = false;
                isSlidingToLast = false;
                break;
            }
        }
    }

    private void initLine(View view, int i) {
        isLastPage = false;
        lineToday.setBackgroundColor(getResources().getColor(R.color.line));
        lineWeek.setBackgroundColor(getResources().getColor(R.color.line));
        lineMonth.setBackgroundColor(getResources().getColor(R.color.line));
        lineAll.setBackgroundColor(getResources().getColor(R.color.line));

        view.setBackgroundColor(getResources().getColor(R.color.white));
        if (TextUtils.isEmpty(userid)) {
            relativeLayoutMyRank.setVisibility(View.GONE);
        } else {
            relativeLayoutMyRank.setVisibility(View.VISIBLE);
        }
        presenter.testRank(libid, userid, String.valueOf(i), "10", String.valueOf(page));
        showLoading();

        list.clear();

        adapter.notifyDataSetChanged();
    }
}
